//
//  ECAlertTool.m
//  ERPChargeAccount2
//
//  Created by 刘思麟 on 2018/6/8.
//  Copyright © 2018年 历山大亚. All rights reserved.
//

#import "ECAlertTool.h"
#import <objc/runtime.h>

@interface ECAlertTool () {
    CGFloat _defaltWidth;
    UIView * _alertView;
}

@property (nonatomic,strong) UIWindow * alertWindow;

@property (nonatomic,strong) UIView * contentView;

@property (nonatomic,strong) UIView * naviView;

@property (nonatomic,strong) UIView * bottomToolView;

- (void)hidden;//隐藏

@end

@implementation ECAlertTool

- (instancetype)init {
    if (self = [super init]) {
        objc_property_attribute_t type = {"T",[[NSString stringWithFormat:@"@\"%@\"",NSStringFromClass([self class])] UTF8String]};
        objc_property_attribute_t ownership = { "&","N"};
        objc_property_attribute_t backingivar  = { "V", "_alertTool"};
        objc_property_attribute_t pa[] = {type,ownership,backingivar};
        BOOL isSuccess = class_addProperty([[UIApplication sharedApplication].delegate class], "alertTool", pa, 3);
        if (isSuccess) {
            //添加get和set方法
            class_addMethod([[UIApplication sharedApplication].delegate class], NSSelectorFromString(@"alertTool"), (IMP)getter, "@@:");
            class_addMethod([[UIApplication sharedApplication].delegate class], NSSelectorFromString(@"setAlertTool:"), (IMP)setter, "v@:@");
        }
        
        _defaltWidth = CGRectGetWidth([UIScreen mainScreen].bounds) - 60 * CGRectGetWidth([UIScreen mainScreen].bounds) / 375;
    }
    return self;
}

- (instancetype)initWithAlertView:(UIView *)view {
    ECAlertTool * tool = [self init];
    if (tool) {
        _alertView = view;
    }
    return tool;
}

- (void)layOutViews {
    [self.alertWindow removeAllSubviews];
    [self.alertWindow addSubview:self.contentView];
    [self.contentView addSubview:self.naviView];
    [self.contentView addSubview:_alertView];
    WS(weakSelf, self);
    UILabel * titleLB;
    if (self.title) {
        titleLB = [[UILabel alloc] init];
        titleLB.font = ECFONT(20);
        titleLB.textColor = ECCOLOR_FONT_TITLE;
        titleLB.text = self.title;
        titleLB.adjustsFontSizeToFitWidth = YES;
        [self.naviView addSubview:titleLB];
        [titleLB mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(weakSelf.naviView).mas_offset(-1);
            make.left.mas_equalTo(weakSelf.naviView).mas_offset(12);
        }];
        UIView * bottomLin = [UIView new];
        bottomLin.backgroundColor = [UIColor colorWithRGB:0x2585e5];
        [self.naviView addSubview:bottomLin];
        [bottomLin mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(titleLB);
            make.bottom.mas_equalTo(weakSelf.naviView);
            make.width.mas_equalTo(20);
            make.height.mas_equalTo(2);
        }];
    }
    if ([_alertView viewController].rightItem) {
        UIView * rightItem = [_alertView viewController].rightItem;
        CGSize size = rightItem.bounds.size;
        [self.naviView addSubview:rightItem];
        WS(weakTitleLB, titleLB);
        [rightItem mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(weakTitleLB?weakTitleLB:weakSelf.naviView);
            make.right.mas_equalTo(weakSelf.naviView).mas_offset(-12);
            make.width.mas_offset(size.width);
            make.height.mas_offset(size.height);
        }];
    }
    
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        ECSTRONG(_strongSelf, weakSelf);
        make.center.mas_equalTo(weakSelf.alertWindow);
        make.width.mas_equalTo(_strongSelf -> _alertView.width > _strongSelf -> _defaltWidth?:_strongSelf -> _defaltWidth);
        make.height.mas_equalTo(60 * PX_RELATIVE375 + _strongSelf -> _alertView.height);
    }];
    
    [self.naviView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(self.contentView);
        make.height.mas_equalTo(30 * PX_RELATIVE375);
    }];
    
    [_alertView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(weakSelf.contentView);
        make.top.mas_equalTo(weakSelf.naviView.mas_bottom);
        make.bottom.mas_equalTo(weakSelf.contentView);
    }];
    
    switch (self.alertType) {
        case ECAlertTypeDefalt:{
            [self.contentView addSubview:self.bottomToolView];
            [self.bottomToolView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.bottom.mas_equalTo(weakSelf.contentView);
                make.height.mas_equalTo(30 * PX_RELATIVE375);
            }];
            
            UIButton * cancelBT = [UIButton buttonWithType:UIButtonTypeCustom];
            [cancelBT setTitle:@"取消" forState:UIControlStateNormal];
            [cancelBT setTitleColor:ECCOLOR_FONT_TITLE forState:UIControlStateNormal];
            [self.bottomToolView addSubview:cancelBT];
            [cancelBT mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.mas_equalTo(weakSelf.bottomToolView);
                make.left.mas_equalTo(12 * PX_RELATIVE375);
            }];
            [cancelBT addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];
            
            UIButton * makeSureBT = [UIButton buttonWithType:UIButtonTypeCustom];
            [makeSureBT setTitle:@"选好了" forState:UIControlStateNormal];
            [makeSureBT setTitleColor:ECCOLOR_FONT_TITLE forState:UIControlStateNormal];
            [self.bottomToolView addSubview:makeSureBT];
            [makeSureBT mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.mas_equalTo(weakSelf.bottomToolView);
                make.right.mas_equalTo(-12 * PX_RELATIVE375);
            }];
            [makeSureBT addTarget:self action:@selector(makeSureAction) forControlEvents:UIControlEventTouchUpInside];
            
            [_alertView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.bottom.mas_equalTo(weakSelf.contentView).mas_offset(-30 * PX_RELATIVE375);
            }];
        }
            break;
        case ECAlertTypeCancelOnly:{
            [self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.centerY.mas_equalTo(weakSelf.alertWindow).mas_offset(-20 * PX_RELATIVE375);
            }];
            UIButton * bt = [UIButton buttonWithType:UIButtonTypeCustom];
            [bt setTitle:@"关闭" forState:UIControlStateNormal];
            bt.titleLabel.font = ECFONT(8);
            [bt addTarget:self action:@selector(hidden) forControlEvents:UIControlEventTouchUpInside];
            [self.alertWindow addSubview:bt];
            [bt mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(weakSelf.alertWindow);
                make.top.mas_equalTo(weakSelf.contentView.mas_bottom).mas_offset(20 * PX_RELATIVE375);
                make.width.height.mas_equalTo(20 * PX_RELATIVE375);
            }];
        }
            break;
        default:
            break;
    }
}

- (void)cancelAction {
    if (self.cancelBlock) {
        self.cancelBlock();
    }
    [self hidden];
}
    
- (void)makeSureAction {
    if (self.makeSureBlock) {
        self.makeSureBlock();
    }
    [self hidden];
}
    
- (void)show {
    [self layOutViews];
    [(NSObject*)[UIApplication sharedApplication].delegate setValue:self forKey:@"alertTool"];
    [self.alertWindow makeKeyAndVisible];
    self.alertWindow.alpha = 0;
    [UIView animateWithDuration:0.25 animations:^{
        self.alertWindow.alpha = 1.0;
    }];
}

- (void)hidden {
    [(NSObject*)[UIApplication sharedApplication].delegate setValue:nil forKey:@"alertTool"];
    [self.alertWindow resignKeyWindow];
    self.alertWindow.hidden = YES;
}

- (UIWindow *)alertWindow {
    if (!_alertWindow) {
        _alertWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _alertWindow.windowLevel = UIWindowLevelAlert;
        _alertWindow.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
        __weak typeof(self) _weakSelf = self;
        [_alertWindow addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
            [_weakSelf hidden];
        }]];
    }
    return _alertWindow;
}

- (UIView *)contentView {
    if (!_contentView) {
        _contentView = [UIView new];
        _contentView.backgroundColor = [UIColor whiteColor];
        _contentView.layer.cornerRadius = 6;
        _contentView.clipsToBounds = YES;
        [_contentView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
            
        }]];
    }
    return _contentView;
}

- (UIView *)naviView {
    if (!_naviView) {
        _naviView = [[UIView alloc] init];
    }
    return _naviView;
}

- (UIView *)bottomToolView {
    if (!_bottomToolView) {
        _bottomToolView = [[UIView alloc] init];
    }
    return _bottomToolView;
}

id getter(id self1, SEL _cmd1) {
    return objc_getAssociatedObject(self1, @"_alertTool");
}

void setter(id self1, SEL _cmd1, id newValue) {
    objc_setAssociatedObject(self1, "_alertTool", newValue, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void)dealloc {
    
}

@end

@implementation UIViewController (ECAlert)

- (void)setRightItem:(UIView *)rightItem {
    objc_setAssociatedObject(self, "_rightItem", rightItem, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIView *)rightItem {
    return objc_getAssociatedObject(self, "_rightItem");
}

@end
